package org.wx.io.netty.rpc.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;
import org.wx.io.netty.rpc.protocol.MyContent;
import org.wx.io.netty.rpc.protocol.MyHeader;
import org.wx.io.netty.rpc.protocol.PackMsg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.util.List;

/**
 * @description: Rpc 解码器
 * @author: wangxun
 * @createDate: 2021/2/23
 * @version: 1.0
 */
@Slf4j
public class RpcDecoder extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("RpcDecoder 被调用 开始解码");

        // 读取头
        int flag = in.readInt();
        long requestId = in.readLong();
        int dataLen = in.readInt();
        byte[] contentBytes = new byte[dataLen];
        in.readBytes(contentBytes);
        // 读取内容 -> 对象反序列化 -> 内容对象
        ByteArrayInputStream bai = new ByteArrayInputStream(contentBytes);
        ObjectInputStream ois = new ObjectInputStream(bai);
        MyContent myContent = (MyContent) ois.readObject();

        MyHeader myHeader = new MyHeader();
        myHeader.setFlag(flag);
        myHeader.setRequestId(requestId);
        myHeader.setDataLen(dataLen);
        // 封装
        PackMsg packMsg = new PackMsg(myHeader, myContent);
        // 让后续的handler进行处理
        out.add(packMsg);
    }
}
